package com.wf.smartcomm.server.admin.action;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.wf.smartcomm.server.bean.User;
import com.wf.smartcomm.server.service.UnitMachService;
import com.wf.smartcomm.server.service.UserService;
import com.wf.smartcomm.server.util.ConstantUtils;


/** 
 * @author 38884306@qq.com  
 * @version 创建时间：2015-5-21 下午5:20:23 
 * 
 */
@Controller(value="adminLoginAction")
@Scope("prototype")
public class LoginAction extends BaseAction {
	
	private String username;
	private String password;
	
	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	@Resource
	private UserService userServiceImpl;
	
	public void login() throws IOException {
		User user = new User();
		user.setUsername(username);
		user.setPassword(password);
		user = userServiceImpl.login(user);
		if (user == null) {
			printJsonData(403);
			return;
		}

		if (user.getType().equals(ConstantUtils.USER_TYPE_ADMIN)) {
			session.setAttribute("loginUser", user);
			session.setAttribute("user", user);
			Cookie cookie = new Cookie("userId",user.getObjectId());
			cookie.setMaxAge(3600*24*30*12*2);
			response.addCookie(cookie);
//			userServiceImpl.counts(user.getLoginVillage(),page);
//			session.setAttribute("userCounts", page.getTotalCount());
//			umServiceImpl.counts(user.getLoginVillage(),page);
//			session.setAttribute("umCounts", page.getTotalCount());
			printJsonData(209);
		}
		
		if (user.getType().equals(ConstantUtils.USER_TYPE_PROPERTY)) {
			session.setAttribute("loginUser", user);
			session.setAttribute("user", user);
//			userServiceImpl.counts(user.getLoginVillage(),page);
//			session.setAttribute("userCounts", page.getTotalCount());
//			umServiceImpl.counts(user.getLoginVillage(),page);
//			session.setAttribute("umCounts", page.getTotalCount());
			printJsonData(203);
		}
		
		if (user.getType().equals(ConstantUtils.USER_TYPE_CENTER)) {
			session.setAttribute("loginUser", user);
			session.setAttribute("user", user);
			printJsonData(outGson.toJson(user));
		}
		
	}	
	
	public String logout() {
		if (session != null) {
			session.invalidate();
//			session.removeAttribute("userCounts");
//			session.removeAttribute("umCounts");
		}
		
		Cookie[] cookies = request.getCookies();
        for(int i = 0,len = cookies.length; i < len; i++) {
            Cookie cookie = new Cookie(cookies[i].getName(),null);
            cookie.setMaxAge(0);
            //cookie.setPath("/");
            response.addCookie(cookie);
        }
        
		return "success";
	}
}
